<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="预约编号" prop="appointmentNo">
        <el-input
          v-model="queryParams.appointmentNo"
          placeholder="请输入预约编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者ID" prop="patientId">
        <el-input
          v-model="queryParams.patientId"
          placeholder="请输入患者ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="患者姓名" prop="patientName">
        <el-input
          v-model="queryParams.patientName"
          placeholder="请输入患者姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="医生姓名" prop="doctorName">
        <el-input
          v-model="queryParams.doctorName"
          placeholder="请输入医生姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预约日期" prop="appointDate">
        <el-date-picker clearable
          v-model="queryParams.appointDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预约日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="时间段" prop="timeSlot">
        <el-input
          v-model="queryParams.timeSlot"
          placeholder="请输入时间段"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:appointment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:appointment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:appointment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:appointment:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="appointmentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="预约编号" align="center" prop="appointmentNo" />
      <el-table-column label="患者ID" align="center" prop="patientId" />
      <el-table-column label="患者姓名" align="center" prop="patientName" />
      <el-table-column label="医生姓名" align="center" prop="doctorName" />
      <el-table-column label="预约日期" align="center" prop="appointDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.appointDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间段" align="center" prop="timeSlot" />
      <el-table-column label="状态(0:待确认 1:已预约 2:已取消 3:已完成)" align="center" prop="status" >
        <template #default="scope">
          <dict-tag :options="sys_appoint_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:appointment:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:appointment:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约主表对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="appointmentRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预约编号" prop="appointmentNo">
          <el-input v-model="form.appointmentNo" placeholder="请输入预约编号" />
        </el-form-item>
        <el-form-item label="患者ID" prop="patientId">
          <el-input v-model="form.patientId" placeholder="请输入患者ID" />
        </el-form-item>
        <el-form-item label="患者姓名" prop="patientName">
          <el-input v-model="form.patientName" placeholder="请输入患者姓名" />
        </el-form-item>
        <el-form-item label="医生姓名" prop="doctorName">
          <el-radio-group v-model="form.doctorName">
            <el-radio v-for="(item, index) in doctorList" :key="index"
                      :label="item">{{ item }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="预约日期" prop="appointDate">
          <el-date-picker clearable
            v-model="form.appointDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择预约日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="时间段" prop="timeSlot">
          <el-input v-model="form.timeSlot" placeholder="请输入时间段" />
        </el-form-item>
        <el-form-item label="预约状态" prop="status">
          <template #default="scope">
            <el-select v-model="form.status" placeholder="请选择状态(0:待确认 1:已预约 2:已取消 3:已完成)">
              <el-option v-for="dict in sys_appoint_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </template>
        </el-form-item>
        <el-divider content-position="center">就诊记录子信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddVisitRecord">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteVisitRecord">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="visitRecordList" :row-class-name="rowVisitRecordIndex" @selection-change="handleVisitRecordSelectionChange" ref="visitRecord">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="签到时间" prop="checkInTime" width="240">
            <template #default="scope">
              <el-date-picker clearable
                v-model="scope.row.checkInTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择签到时间">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="诊断结果" prop="diagnosis" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.diagnosis" placeholder="请输入诊断结果" />
            </template>
          </el-table-column>
          <el-table-column label="状态(0:待就诊 1:就诊中 2:已完成)" prop="status" width="150">
            <template #default="scope">
              <el-select v-model="scope.row.status" placeholder="请选择状态(0:待就诊 1:就诊中 2:已完成)">
                <el-option v-for="dict in sys_appointment_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Appointment">
import { listAppointment, getAppointment, delAppointment, addAppointment, updateAppointment,getPatientByDoctorName } from "@/api/system/appointment"
import {useDict} from "@/utils/dict.js";
import { listDoctors } from "@/api/system/doctors"

const {sys_appointment_status,sys_appoint_status} = useDict("sys_appointment_status","sys_appoint_status")
const { proxy } = getCurrentInstance()

const appointmentList = ref([])
const visitRecordList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedVisitRecord = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const doctorList = ref([])
const patientNumber = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appointmentNo: null,
    patientId: null,
    patientName: null,
    doctorId: null,
    doctorName: null,
    appointDate: null,
    timeSlot: null,
    status: null,
  },
  rules: {
    appointmentNo: [
      { required: true, message: "预约编号不能为空", trigger: "blur" }
    ],
    patientId: [
      { required: true, message: "患者ID不能为空", trigger: "blur" }
    ],
    patientName: [
      { required: true, message: "患者姓名不能为空", trigger: "blur" }
    ],
    doctorId: [
      { required: true, message: "医生ID不能为空", trigger: "blur" }
    ],
    doctorName: [
      { required: true, message: "医生姓名不能为空", trigger: "blur" }
    ],
    appointDate: [
      { required: true, message: "预约日期不能为空", trigger: "blur" }
    ],
    timeSlot: [
      { required: true, message: "时间段不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态(0:待确认 1:已预约 2:已取消 3:已完成)不能为空", trigger: "change" }
    ],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)


/**获取医生姓名列表*/
listDoctors().then(async response => {
  console.log(response.rows)
  doctorList.value = response.rows.map(doctor => doctor.name)
  console.log(doctorList.value)
  console.log(doctorList.value[0])
})

/** 查询预约主表列表 */
function getList() {
  loading.value = true
  listAppointment(queryParams.value).then(response => {
    appointmentList.value = response.rows
    total.value = response.total
    loading.value = false
    //console.log(appointmentList.value)
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    appointmentNo: null,
    patientId: null,
    patientName: null,
    doctorId: null,
    doctorName: null,
    appointDate: null,
    timeSlot: null,
    status: null,
    createTime: null
  }
  visitRecordList.value = []
  proxy.resetForm("appointmentRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加预约主表"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getAppointment(_id).then(response => {
    form.value = response.data
    visitRecordList.value = response.data.visitRecordList
    open.value = true
    title.value = "修改预约主表"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["appointmentRef"].validate(valid => {
    if (valid) {
      form.value.visitRecordList = visitRecordList.value
      if (form.value.id != null) {
        updateAppointment(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addAppointment(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除预约主表编号为"' + _ids + '"的数据项？').then(function() {
    return delAppointment(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 就诊记录子序号 */
function rowVisitRecordIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 就诊记录子添加按钮操作 */
function handleAddVisitRecord() {
  let obj = {}
  obj.checkInTime = ""
  obj.diagnosis = ""
  obj.status = ""
  visitRecordList.value.push(obj)
}

/** 就诊记录子删除按钮操作 */
function handleDeleteVisitRecord() {
  if (checkedVisitRecord.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的就诊记录子数据")
  } else {
    const visitRecords = visitRecordList.value
    const checkedVisitRecords = checkedVisitRecord.value
    visitRecordList.value = visitRecords.filter(function(item) {
      return checkedVisitRecords.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleVisitRecordSelectionChange(selection) {
  checkedVisitRecord.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/appointment/export', {
    ...queryParams.value
  }, `appointment_${new Date().getTime()}.xlsx`)
}

getList()
</script>
